/**
 * Created by yunpeng on 2015/3/26.
 */
var starterModule = angular.module('starter',['starter.controllers','starter.orderControllers','starter.centerControllers', 'starter.services','starter.centerSrvices','starter.orderServices','ui.router','ngAnimate'])
    .run(['$rootScope', '$state', '$stateParams','$window','AuthenticationService',function($rootScope, $state, $stateParams,$window,AuthenticationService) {

   /*     $rootScope.$on('$routeChangeStart', function(event, next, current) {
            //redirect only if both isLogged is false and no token is set
            if (next != null && next.access != null && next.access.requiredLogin
                && !AuthenticationService.isLogged && !$window.sessionStorage.token) {

                $state.go('/');
            }
        });*/

        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
            if (toState != null && toState.access != null && toState.access.requiredLogin
                && !AuthenticationService.isLogged && !localStorage.getItem('token')) {//判断token状态，验证失败阻止进入其他url//$window.sessionStorage.token

                $state.go('login');
                event.preventDefault();
            }

            if(toState.url.indexOf('transfer')>-1){
                setCo();
                changeCo(1);

            }else if(toState.url.indexOf('myTransfer')>-1){
                setCo();
                changeCo(2);

            }else if(toState.url.indexOf('myOrders')>-1){
                setCo();
                changeCo(3);

            }else if(toState.url.indexOf('center')>-1){
                setCo();
                changeCo(4);
            }

            /*$rootScope.setColor = function(index){
                setCo();
                changeCo(index);
                console.log('sss');
            }*/
            function setCo(){
                $rootScope.num1=2;
                $rootScope.num2=2;
                $rootScope.num3=2;
                $rootScope.num4=2;
            }

            function changeCo(index){
                switch (index){
                    case 1:
                        $rootScope.num1=1;
                        break;
                    case 2:
                        $rootScope.num2=1;
                        break;
                    case 3:
                        $rootScope.num3=1;
                        break;
                    case 4:
                        $rootScope.num4=1;
                        break;
                }
            }

        });


        $rootScope.goMain = function(){
            $state.go('/');
        }
        }
    ])
    .config(['$stateProvider', '$urlRouterProvider','$httpProvider',function($stateProvider, $urlRouterProvider,$httpProvider){
        $httpProvider.interceptors.push('TokenInterceptor');
        $stateProvider
            .state('login',{
                url:'/login',
                templateUrl:'view/logon/login.html',
                controller:'LoginCtrl'
         })
            .state('/',{
                url:'/',
                templateUrl:'view/main/main.html',
                controller:'MainCtrl',
                access: { requiredLogin: false }
            })
            .state('tab',{
                url:'/tab',
                abstract:true,
                templateUrl:'view/tabs.html',
                /*controller:'TabCtrl',*/
                access: { requiredLogin: true }
            })
            .state('tab.transfer',{
                url:'/transfer',
                templateUrl:'view/transfer/transfer.html',
                controller:'TransferCtrl',
                access: { requiredLogin: true }

         })
            .state('tab.myTransfer',{
                url:'/myTransfer/:random',
                templateUrl:'view/transfer/myTransfer.html',
                controller:'MyTransferCtrl',
                access: { requiredLogin: true }
            })
            .state('query',{
                url:'/query/:isWechat',
                templateUrl:'view/query/query.html',
                controller:'Query'
            })
            .state('tab.myOrders',{
                url:'/myOrders',
                templateUrl:'view/order/order1.html',
                controller:'MyOrderCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.center',{
                url:'/center',
                templateUrl:'view/center/center.html',
                controller:'CenterCtrl',
                access: { requiredLogin: true }
            })
            .state('register',{
                url:'/register',
                templateUrl:'view/logon/register.html',
                controller:'RegisterCtrl'
            })
            .state('resetPass',{
                url:'/resetPass',
                templateUrl:'view/logon/resetPass.html',
                controller:'ResetPassCtrl'
            })
            .state('tab.outDetails',{
                url:'/myTransfer/outDetails/:startstation/:endstation/:starttime/:endtime/:type/:num/:carnum/:nums/:infoid',
                templateUrl:'view/transfer/outDetails.html',
                controller:'OutDetails',
                access: { requiredLogin: true }
            })
            .state('tab.myTransfer2',{
                url:'/myTransfer/myTransfer2/:inforid/:name/:phone',
                templateUrl:'view/transfer/myTransfer2.html',
                controller:'myTransfer2',
                access: { requiredLogin: true }
            })
            .state('tab.companyDet',{
                url:'/myTransfer/companyDet/:inforid/:userid',
                templateUrl:'view/transfer/companyDet.html',
                controller:'companyDet',
                access: { requiredLogin: true }
            })
            .state('tab.citys',{
                url:'/citys/:type',//1始发地 2目的地
                templateUrl:'view/transfer/citys.html',
                controller:'CitysCtrl'/*,
                access: { requiredLogin: true }*/
            })
            .state('AddCitys',{
                url:'/AddCitys/:type',//1始发地 2目的地
                templateUrl:'view/query/citys.html',
                controller:'AddCitys'/*,
                access: { requiredLogin: true }*/
            })
            .state('tab.transferAddCar',{
                url:'/transferAddCar',//1始发地 2目的地
                templateUrl:'view/transfer/transferAddCar.html',
                controller:'TransferAddCarCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.getCarBrandList',{
                url:'/getCarBrandList',//1始发地 2目的地
                templateUrl:'view/transfer/carbrand.html',
                controller:'CarBrandListCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.getCarNumList',{
                url:'/getCarNumList',//1始发地 2目的地
                templateUrl:'view/transfer/carnum.html',
                controller:'CarNumListCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.carlist',{
                url:'/carlist',//1始发地 2目的地
                templateUrl:'view/transfer/carlist.html',
                controller:'CarListCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.complete',{
                url:'/complete/:isOk',//1始发地 2目的地
                templateUrl:'view/transfer/complete.html',
                controller:'CompleteCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.completeQuo',{  //接受报价后
                url:'/completeQuo/:isOk',
                templateUrl:'view/transfer/complete01.html',
                controller:'CompleteCtrlQuo',
                access: { requiredLogin: true }
            })
            .state('tab.cropper',{
                url:'/cropper/:scale1/:scale2/:width/:height/:urltype',//
                templateUrl:'view/cropper.html',
                controller:'CropperCtrl',
                access: { requiredLogin: true }
            });
         $urlRouterProvider.otherwise('/');
    }])
   .directive('ngLoad',['$http','$compile','MyTransferService','$stateParams',function($http,$compile,MyTransferService,$stateParams){//自定义指令
    return{
        restrict: 'A',//
        templateUrl:'./view/transfer/ulcontent.html',
        link:function(scope,element,attrs,controller){
            $('#contentu').css('min-height',$(window).height()-92+'px');
            scope.query = {sort:'createtime',order:'desc',page:1,rows:10};
            //初始化列表
            var arrs=[];
            if($stateParams.random=='update'){
                scope.query.page=1;//从第一页开始查询
                var  promise = $http({
                    method:'POST',
                    url:'/myTransfer',
                    data:{
                        query : {sort:'createtime',order:'desc',page:1,rows:10}
                    }
                });
                promise.success(function(data,status) {
                    var arrss=[];
                    scope.datas = data.rows;
                    MyTransferService.getMytransferData().datas = scope.datas;//更新service数据
                    scope.query.page+=1;//查询成功页数加一
                    for(var i=0;i<data.rows.length;i++){
                        var arr=data.rows[i].num.split(',');
                        var ss=0;
                        for(var j=0;j<arr.length;j++){
                            ss += parseInt(arr[j]);
                        }
                        arrss.push(ss);
                    }
                    scope.nums=arrss;
                    setTimeout(function(){//因为有冲突等会执行scope.$apply();
                        scope.$apply(element);
                        if(scope.myScroll){
                            scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                        }
                    },500);});
            }else{
                if(!MyTransferService.getMytransferData().datas.length>0){//判断数据是否加载过，存在不去请求服务器
                    var  promise = $http({
                        method:'POST',
                        url:'/myTransfer',
                        data:{
                            query:scope.query
                        }
                    });
                    promise.success(function(data,status) {
                        scope.datas = data.rows;
                        MyTransferService.getMytransferData().datas = scope.datas;
                        scope.query.page+=1;
                        /*  var num=data.rows[0].num;
                         var nums=num.split(",");*/
                        for(var i=0;i<scope.datas.length;i++){
                            var arr=scope.datas[i].num.split(',');
                            var ss=0;
                            for(var j=0;j<arr.length;j++){
                                ss += parseInt(arr[j]);
                            }
                            arrs.push(ss);
                        }
                        scope.nums=arrs;
                        setTimeout(function(){//因为有冲突等会执行scope.$apply();
                            scope.$apply(element);
                            if(scope.myScroll){
                                scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        },500);
                    });

                }
            }
            //angular.element(element.children().eq(0)).toggleClass('a1');
            function pullDownAction(){//下拉刷新调用
                /* var el, li, i;*/
                 //el = document.querySelector("#scroller ul");
                    /*for (i=0; i<3; i++) {
                    li = document.createElement("li");
                    li.innerHTML = $compile('<input type="button" ng-click="alert1()" value="dddddd"/>')(scope);//Firefox  does not suppose innerText, use innerHTML instead.)//Firefox  does not suppose innerText, use innerHTML instead.
                    el.insertBefore(li, el.childNodes[0]);
                    }
                       var dd = $compile('<input type="button" ng-click="alert1()" value="dddddd"/><input type="button" ng-click="alert1()" value="ddddddaaddd"/>' +
                       '<div style="color: #CD235C;height: 3em;">asdsad</div>')(scope);
                       element.append(dd);*/
            }
            pull(scope,"wrapper",function(pull){
                if('pullDown'==pull) {//下拉刷新
                    scope.query.page=1;//从第一页开始查询
                    var  promise = $http({
                        method:'POST',
                        url:'/myTransfer',
                        data:{
                            query : scope.query
                        }
                    });
                    promise.success(function(data,status) {
                        scope.datas = data.rows;
                        MyTransferService.getMytransferData().datas = scope.datas;//更新service数据
                        scope.query.page+=1;//查询成功页数加一
                        setTimeout(function(){//因为有冲突等会执行scope.$apply();
                            scope.$apply(element);
                            if(scope.myScroll){
                                scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        },500);

                    }).error(function (data,status) {
                        if(scope.myScroll){
                            scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                        }
                    });
                }else{
                    var  promise = $http({
                        method:'POST',
                        url:'/myTransfer',
                        data:{
                            query : scope.query
                        }
                    });
                    promise.success(function(data) {
                        scope.query.page+=1;//查询成功页数加一
                        if(data.rows.length>0){
                            scope.datas = scope.datas.concat(data.rows);
                            MyTransferService.getMytransferData().datas = scope.datas;//service更新数据
                            var num=data.rows[0].num;
                            var nums=num.split(",");
                            for(var i=0;i<data.rows.length;i++){
                                var arr=data.rows[i].num.split(',');
                                var ss=0;
                                for(var j=0;j<arr.length;j++){
                                    ss += parseInt(arr[j]);
                                }
                                arrs.push(ss);
                            }
                            scope.nums=arrs;
                        }

                        setTimeout(function(){//因为有冲突等会执行scope.$apply();
                            scope.$apply(element);
                            if(scope.myScroll){
                                scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        },500);

                    }).error(function (data,status) {
                        if(scope.myScroll){
                            scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                        }
                    });
                }
            });
            //初始化绑定iScroll控件
            document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
            //document.addEventListener('DOMContentLoaded', loaded, false);

            if(MyTransferService.getMytransferData().datas.length>0){//待myScroll初始化完成后刷新页面数据
                scope.datas = MyTransferService.getMytransferData().datas;
                scope.query.page+=1;
                for(var i=0;i<scope.datas.length;i++){
                    var arr=scope.datas[i].num.split(',');
                    var ss=0;
                    for(var j=0;j<arr.length;j++){
                        ss += parseInt(arr[j]);
                    }
                    arrs.push(ss);
                }
                scope.nums=arrs;
                setTimeout(function(){//因为有冲突等会执行scope.$apply();
                    scope.$apply(element);
                    if(scope.myScroll){
                        scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                    }
                },500);
                return;
            }


        }
    }
}]).directive('ngLoaded',['$http','$compile','$stateParams',function($http,$compile,$stateParams){//自定义指令
        return{
            restrict: 'A',//
            templateUrl:'./view/transfer/quotation.html',
            link:function(scope,element,$state,attrs,controller){
                $('#content').css('min-height',$(window).height()-92+'px');
                //初始化列表

                scope.query = {sort:'starttime',order:'desc',page:1,rows:10};
                var inforid=$stateParams.inforid;
                var name=$stateParams.name;
                var myphone=$stateParams.phone;
                var  promise = $http({
                    method:'POST',
                    url:'/quotation',
                    data:{
                        query:scope.query,
                        inforid:inforid
                    }
                });
                promise.success(function(data) {
                    scope.query.page+=1;
                    scope.datas = data.rows;
                    scope.name=name;
                    scope.myphone=myphone;
                    if(data.rows.length==0){
                        scope.show=true;
                    }else{
                        scope.show=false;
                    }
                    scope.inforid=inforid;
                    scope.graderArray=[{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"}];
                    setTimeout(function(){//因为有冲突等会执行scope.$apply();
                        scope.$apply(element);
                        if(scope.myScroll){
                            scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)

                        }
                    },500);
                });
                //angular.element(element.children().eq(0)).toggleClass('a1');
                function pullDownAction(){//下拉刷新调用
                    /* var el, li, i;*/
                    //el = document.querySelector("#scroller ul");
                    /*for (i=0; i<3; i++) {
                     li = document.createElement("li");
                     li.innerHTML = $compile('<input type="button" ng-click="alert1()" value="dddddd"/>')(scope);//Firefox  does not suppose innerText, use innerHTML instead.)//Firefox  does not suppose innerText, use innerHTML instead.
                     el.insertBefore(li, el.childNodes[0]);
                     }
                     var dd = $compile('<input type="button" ng-click="alert1()" value="dddddd"/><input type="button" ng-click="alert1()" value="ddddddaaddd"/>' +
                     '<div style="color: #CD235C;height: 3em;">asdsad</div>')(scope);
                     element.append(dd);*/
                }
                pull(scope,"wrapper",function(pull){
                    if('pullDown'==pull) {//下拉刷新
                        scope.query.page=1;
                        var  promise = $http({
                                method:'POST',
                                url:'/quotation',
                                data:{
                                    query:scope.query,
                                    inforid:inforid
                                }
                            });
                            promise.success(function(data) {
                                scope.query.page+=1;
                                scope.datas = data.rows;
                                scope.graderArray=[{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"}];
                                setTimeout(function(){//因为有冲突等会执行scope.$apply();
                                    scope.$apply(element);
                                    if(scope.myScroll){
                                        scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                                    }
                                },500);

                        }).error(function (data,status) {
                            if(scope.myScroll){
                                scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        });
                    }else{
                        var  promise = $http({
                            method:'POST',
                            url:'/quotation',
                            data:{
                                query:scope.query,
                                inforid:inforid
                            }
                        });
                        promise.success(function(data) {
                            scope.query.page+=1;
                            scope.datas = scope.datas.concat(data.rows);
                            scope.graderArray=[{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"}];
                            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                                scope.$apply(element);
                                if(scope.myScroll){
                                    scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                                }
                            },500);

                        }).error(function (data,status) {
                            if(scope.myScroll){
                                scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        });
                    }
                });
                //初始化绑定iScroll控件
                document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
                //document.addEventListener('DOMContentLoaded', loaded, false);

            }
        }
    }]).directive('ngSlider',['$http','$compile',function($http,$compile){//自定义指令
        return{
            restrict: 'A',//
            //templateUrl:'./view/transfer/quotation.html',
            link:function(scope,element,attrs,controller){


            }
        }
    }]);

/**
 * 下拉刷新调用此方法回调callback(pull) pull=='pullDown'下拉 pull=='pullUp'上拉
 * @param scope
 * @param callback
 */
function pull(scope,id,callback){
    scope.myScroll="#"+id;
    // var myScroll,
    scope.pullDownEl= 0;
    scope.pullDownOffset= 0;
    scope.pullUpEl= 0;
    scope.pullUpOffset= 0;
    scope.generatedCount = 0;

    //function loaded() {
    scope.pullDownEl = document.querySelector("#pullDown");
    if (scope.pullDownEl) {
        scope.pullDownOffset = scope.pullDownEl.offsetHeight;
    } else {
        scope.pullDownOffset = 0;
    }
    scope.pullUpEl = document.querySelector("#pullUp");
    if (scope.pullUpEl) {
        scope.pullUpOffset = scope.pullUpEl.offsetHeight;
    } else {
        scope.pullUpOffset = 0;
    }

    console.log(" scope.pullDownOffset:"+ scope.pullDownOffset);
    console.log("scope.pullUpOffset:"+scope.pullUpOffset);

    //Options of IScroll
    var myOptions = {
        mouseWheel: true,click:true,
        scrollbars: false,
        fadeScrollbars: true,
        probeType: 1,
        startY: - scope.pullDownOffset
    };
    scope.myScroll = new IScroll("#"+id,myOptions);
    console.log("maxScrollY-1:"+scope.myScroll.maxScrollY);
    _maxScrollY = scope.myScroll.maxScrollY = scope.myScroll.maxScrollY + scope.pullUpOffset;
    console.log("maxScrollY-2:"+scope.myScroll.maxScrollY);

    var isScrolling = false;

    //Event: scrollStart
    scope.myScroll.on("scrollStart", function() {
        if(this.y==this.startY){
            isScrolling = true;
        }
        console.log("start-y:"+this.y);
    });

    //Event: scroll
    scope.myScroll.on("scroll", function(){
        if (this.y >= 5 && scope.pullDownEl && !scope.pullDownEl.className.match("flip")) {
            scope.pullDownEl.className = "flip";
            scope.pullDownEl.querySelector(".pullDownLabel").innerHTML = "释放立即刷新";
            //this.minScrollY = 0;
        } else if (this.y < 5  && scope.pullDownEl && scope.pullDownEl.className.match("flip")) {
            scope.pullDownEl.className = "";
            scope.pullDownEl.querySelector(".pullDownLabel").innerHTML = "下拉刷新";
            //this.minScrollY = - scope.pullDownOffset;
        }else if (this.y <= (_maxScrollY - scope.pullUpOffset) && scope.pullUpEl && !scope.pullUpEl.className.match("flip")) {
            scope.pullUpEl.className = "flip";
            scope.pullUpEl.querySelector(".pullUpLabel").innerHTML = "释放立即刷新";
            //this.maxScrollY = this.maxScrollY;
            this.maxScrollY = this.maxScrollY - scope.pullUpOffset;
        } else if (this.y > (_maxScrollY - scope.pullUpOffset) && scope.pullUpEl && scope.pullUpEl.className.match("flip")) {
            scope.pullUpEl.className = "";
            scope.pullUpEl.querySelector(".pullUpLabel").innerHTML = "上拉加载更多";
            //this.maxScrollY = scope.pullUpOffset;
            this.maxScrollY = this.maxScrollY + scope.pullUpOffset;
        }

        console.log("y:"+this.y);
    });

    //Event: scrollEnd
    scope.myScroll.on("scrollEnd", function() {
        console.log("scroll end");
        console.log("directionY:"+this.directionY);
        console.log("y1:"+this.y);
        console.log("maxScrollY-3:"+this.maxScrollY);
        if (scope.pullDownEl && !scope.pullDownEl.className.match("flip") && this.y > this.options.startY) {
            console.log("resume");
            this.scrollTo(0, this.options.startY,800);
        }
        else if (scope.pullDownEl && scope.pullDownEl.className.match("flip")){
            scope.pullDownEl.className = "loading";
            scope.pullDownEl.querySelector(".pullDownLabel").innerHTML = "加载中...";
            // Execute custom function (ajax call?)
            if (isScrolling) {
                console.log("before pull down action:"+this.y);
                //pullDownAction();
                callback('pullDown');
                console.log("after pull down action:"+this.y);
            }
        }
        else if (scope.pullUpEl && scope.pullUpEl.className.match("flip")) {
            console.log("pull up loading");
            scope.pullUpEl.className = "loading";
            scope.pullUpEl.querySelector(".pullUpLabel").innerHTML = "加载中...";
            // Execute custom function (ajax call?)
            if (isScrolling) {
                console.log("before pull up action:"+this.y);
                //pullUpAction();
                callback('pullUp');

                console.log("after pull up action:"+this.y);
            }
        }
        isScrolling = false;
    });

    //Event: refresh
    scope.myScroll.on("refresh", function() {

        console.log("maxScrollY-4:"+this.maxScrollY);
        _maxScrollY = this.maxScrollY = this.maxScrollY+scope.pullUpOffset;
        console.log("maxScrollY-5:"+this.maxScrollY);

        if (scope.pullDownEl  && scope.pullDownEl.className.match("loading")) {
            scope.pullDownEl.className = "";
            scope.pullDownEl.querySelector(".pullDownLabel").innerHTML = "下拉刷新";
            this.scrollTo(0,this.options.startY,0);
        } else if (scope.pullUpEl && scope.pullUpEl.className.match("loading")) {
            scope.pullUpEl.className = "";
            scope.pullUpEl.querySelector(".pullUpLabel").innerHTML = "上拉加载更多";
            this.scrollTo(0,this.maxScrollY,0);
        }

        console.log("refresh finished!");
    });

    setTimeout(function () { document.getElementById(id).style.left = "0"; }, 800);

    //}

}